// WiFiManager.cpp
#include "WiFiManager.h"
#include <Arduino.h>

WiFiManager::WiFiManager(const char* defaultSSID, const char* defaultPass) {
    strncpy(ssid, defaultSSID, sizeof(ssid));
    strncpy(password, defaultPass, sizeof(password));
}

void WiFiManager::begin() {
    connectToWiFi();
    
    if (!isConnected()) {
        WiFi.softAP("ESP32_Config", "12345678");
        server.on("/", [this]() { handleRoot(); });
        server.on("/config", [this]() { handleConfig(); });
        server.begin();
        apModeActive = true;
        Serial.println(F("AP Mode Started"));
    }
}

void WiFiManager::handleClient() {
    if (apModeActive) server.handleClient();
}

bool WiFiManager::isConnected() { 
    return WiFi.status() == WL_CONNECTED; 
}

bool WiFiManager::isAPMode() { 
    return apModeActive; 
}

void WiFiManager::getCredentials(char* ssidBuf, char* passBuf) {
    strncpy(ssidBuf, ssid, 32);
    strncpy(passBuf, password, 64);
}

void WiFiManager::connectToWiFi() {
    Serial.println(F("\nConnecting to WiFi..."));
    WiFi.begin(ssid, password);
    
    unsigned long startTime = millis();
    while (!isConnected() && millis() - startTime < 10000) {
        delay(500);
        Serial.print(F("."));
    }
    
    if (isConnected()) {
        Serial.print(F("\nConnected! IP: "));
        Serial.println(WiFi.localIP());
        apModeActive = false;
    } else {
        Serial.println(F("\nConnection Failed!"));
    }
}

void WiFiManager::handleRoot() {
    server.send(200, "text/html", 
        F("<!DOCTYPE html><html><head><meta name='viewport' content='width=device-width, initial-scale=1'>"
          "<style>body{font-family:Arial;margin:20px}form{max-width:300px}input{margin:5px 0;padding:8px;width:100%}</style>"
          "</head><body><h2>WiFi Configuration</h2><form action='/config' method='POST'>"
          "SSID:<br><input type='text' name='ssid' required><br>"
          "Password:<br><input type='password' name='password' minlength='8' required><br>"
          "<input type='submit' value='Save'></form></body></html>"));
}

void WiFiManager::handleConfig() {
    if (server.method() == HTTP_POST) {
        String newSSID = server.arg("ssid");
        String newPass = server.arg("password");
        
        if (newSSID.length() > 0 && newPass.length() >= 8) {
            newSSID.toCharArray(ssid, sizeof(ssid));
            newPass.toCharArray(password, sizeof(password));
            
            server.send(200, "text/html", F("<html><body><h1>Settings Saved!</h1><p>Reconnecting...</p></body></html>"));
            delay(1000);
            WiFi.disconnect();
            connectToWiFi();
        } else {
            server.send(400, "text/plain", F("Invalid input"));
        }
    }
}